package com.ita.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ita.pojo.Customer;
import com.ita.service.CustomerManager;
import com.ita.service.CustomerManagerFactory;
import com.ita.util.NumberUtil;

@WebServlet("/regi")
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CustomerManager manager;

	public RegistServlet() {
		super();
		manager = CustomerManagerFactory.getInstance();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// 1 接参
		String cname = request.getParameter("name");
		String csal = request.getParameter("sal");
		String csex = request.getParameter("sex");
		String cbirth = request.getParameter("birth");
		String[] cfavs = request.getParameterValues("favs");
		// 2 校验
		if(cname.length()>4||"".equals(cname)){
			response.sendRedirect("regist.jsp");return;
		}
		if(!NumberUtil.isDouble(csal)||"".equals(csal)||csal.length()>5){
			response.sendRedirect("regist.jsp");
			return;
		}
		if("".equals(cbirth)){
			response.sendRedirect("regist.jsp");return;
		}
		if(cfavs==null||cfavs.length==0){
			response.sendRedirect("regist.jsp");return;
		}
		// 3 类型转换
		Date birth = null;
		double sal = Double.parseDouble(csal);
		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			birth = sdFormat.parse(cbirth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String favs=Arrays.toString(cfavs);
		// 4 封装
		Customer c = new Customer(null, cname, sal, csex, birth, favs);
		int m = manager.addCustomer(c);
		if (m > 0) {
//			request.setAttribute("c", c);
			response.sendRedirect("list");
		} else {
			response.sendRedirect("regist.jsp");
		}

	}

}
